package web.pre;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import entity.User;
import service.EasyBuyService;
import utils.ReturnResult;

public class userIndexServlet extends HttpServlet{ 
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		String action=request.getParameter("action");
		if(action!=null){
			switch (action) {
			case "toRegister":
				toResult(request,response);
				break;
			case "doRegister":
				doResult(request,response);
				break;
			default:
				break;
			}
		}
	}
	private void doResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//将loginUser 移除session
		request.getSession().removeAttribute("User");
		response.sendRedirect("Login.jsp");
	}
	private void toResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");
		String pass = request.getParameter("pass");
		EasyBuyService easy=new EasyBuyService();
		User user=new User();
		user = easy.userDengle(name, pass);
		request.getSession().setAttribute("user", user);
		PrintWriter out =response.getWriter();
		ReturnResult result=new ReturnResult(0,"登录失败");
		if(user!=null){
			
			result.setStatus(1);
			result.setMessage("登录成功");
			
			
			//request.getRequestDispatcher("Index.jsp?action=toReslut").forward(request, response);
		}
		String jsonStr=JSON.toJSONString(result);
		out.print(jsonStr);
		out.flush();
		out.close();
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}
